package com.example.pdfdemo;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api")
public class HtmlToPdfController {

    @PostMapping("/html-to-pdf")
    public ResponseEntity<byte[]> convertHtmlToPdf(@RequestParam("file") MultipartFile file) throws Exception {
        String htmlContent = new String(file.getBytes());
        return convertHtmlToPdfInternal(htmlContent, "converted.pdf");
    }

    @PostMapping("/html-to-pdf/direct")
    public ResponseEntity<byte[]> convertHtmlToPdfDirect(@RequestParam("filePath") String filePath) throws Exception {
        // 安全检查：防止路径遍历攻击
        if (filePath.contains("..") || filePath.startsWith("/")) {
            return ResponseEntity.badRequest().body("非法的文件路径".getBytes(StandardCharsets.UTF_8));
        }

        try {
            // 从 static 目录读取文件
            Resource resource = new ClassPathResource("static/" + filePath);
            if (!resource.exists()) {
                return ResponseEntity.badRequest().body("文件不存在".getBytes(StandardCharsets.UTF_8));
            }

            String htmlContent = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            String fileName = filePath.substring(filePath.lastIndexOf('/') + 1).replace(".html", ".pdf");
            return convertHtmlToPdfInternal(htmlContent, fileName);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body(("读取文件失败: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        }
    }

    private ResponseEntity<byte[]> convertHtmlToPdfInternal(String htmlContent, String fileName) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 配置转换属性，使用系统字体
        ConverterProperties converterProperties = new ConverterProperties();
        FontProvider fontProvider = new DefaultFontProvider(false, false, false);
        FontProgram fontProgram = FontProgramFactory.createFont(new ClassPathResource("font/Poppins-Regular.ttf").getPath());
        FontProgram fontProgramBold = FontProgramFactory.createFont(new ClassPathResource("font/Poppins-SemiBold.ttf").getPath());
        fontProvider.addFont(fontProgram);
        fontProvider.addFont(fontProgramBold);
        fontProvider.addSystemFonts();
        converterProperties.setFontProvider(fontProvider);

        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(writer);
        pdfDocument.setDefaultPageSize(PageSize.LETTER);

        HtmlConverter.convertToPdf(htmlContent, pdfDocument, converterProperties);
        pdfDocument.close();

        byte[] pdfBytes = outputStream.toByteArray();
        outputStream.close();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdfBytes);
    }
}
